<template>
  <div class="im-container">
    <div class="session-list">
      <div class="session-title">会话列表</div>
      <el-scrollbar class="session-scroll">
        <div v-for="session in sessions" :key="session.expertId" :class="['session-item', session.expertId === currentExpertId ? 'active' : '']" @click="selectSession(session)">
          <el-avatar :src="session.expert && session.expert.avatar ? getImageUrl(session.expert.avatar) : ''" size="medium" icon="el-icon-user-solid" />
          <div class="session-info">
            <div class="name">{{ session && session.expert.name }}</div>
            <div class="desc">{{ session && session.expert.email }}</div>
          </div>
        </div>
        <el-empty v-if="!sessions.length" description="暂无会话" />
      </el-scrollbar>
    </div>
    <div class="chat-area" v-if="currentExpertId">
      <div class="chat-header">
        <span>{{ currentSession.expert && currentSession.expert.name }}</span>
        <span class="chat-title-desc">{{ currentSession.expert && currentSession.expert.title }}</span>
      </div>
      <div class="chat-messages" ref="msgBox">
        <div v-for="msg in messages" :key="msg.id" :class="['chat-msg', msg.fromExpert ? 'left' : 'right']">
          <el-avatar :src="msg.fromExpert ? getImageUrl(currentSession.expert.avatar) : userInfo.avatar" size="small" icon="el-icon-user-solid" />
          <div class="bubble">
            <span class="role">{{ msg.fromExpert ? '[专家]' : '[我]' }}</span>
            <span>{{ msg.content }}</span>
            <span class="time">{{ formatTime(msg.sendTime) }}</span>
          </div>
        </div>
      </div>
      <div class="chat-input-row">
        <el-input v-model="input" placeholder="请输入内容..." @keyup.enter.native="send" class="chat-input" />
        <el-button type="primary" @click="send">发送</el-button>
      </div>
    </div>
    <div class="chat-area" v-else>
      <el-empty description="请选择会话" />
    </div>
  </div>
</template>
<script>
import { getUserSessions, getHistory } from '../../api/ChatController';
import { sendChatMessage, connectChatSocket, closeChatSocket } from '../../api/chatSocket';
export default {
  data() {
    return {
      userInfo: JSON.parse(localStorage.getItem('frontUser') || '{}'),
      sessions: [],
      currentExpertId: null,
      currentSession: {},
      messagesMap: {}, // { expertId: [msg, ...] }
      input: '',
      unreadMap: {}, // { expertId: count }
    };
  },
  methods: {
    async loadSessions() {
      const res = await getUserSessions(this.userInfo.id);
      this.sessions = Array.isArray(res) ? res : (res.data || []);
      if (this.sessions.length) {
        this.selectSession(this.sessions[0]);
      }
    },
    async selectSession(session) {
      this.currentExpertId = session.expertId;
      this.currentSession = session;
      // 拉取历史消息
      const res = await getHistory({ userId: this.userInfo.id, expertId: session.expertId });
      this.$set(this.messagesMap, session.expertId, Array.isArray(res) ? res : (res.data || []));
      this.$set(this.unreadMap, session.expertId, 0);
      this.$nextTick(this.scrollToBottom);
    },
    handleSocketMessage(msg) {
      console.log('用户收到消息', msg, this.userInfo.id);
      if (!msg || msg.userId !== this.userInfo.id && msg.expertId !== this.userInfo.id) return;
      const expertId = msg.expertId;
      if (!this.messagesMap[expertId]) this.$set(this.messagesMap, expertId, []);
      this.messagesMap[expertId].push(msg);
      if (this.currentExpertId === expertId) {
        this.$nextTick(this.scrollToBottom);
      } else {
        this.$set(this.unreadMap, expertId, (this.unreadMap[expertId] || 0) + 1);
      }
    },
    send() {
      if (!this.input) return;
      const msg = {
        expertId: this.currentExpertId,
        userId: this.userInfo.id,
        content: this.input,
        fromExpert: false,
        sendTime: new Date().toISOString()
      };
      sendChatMessage(msg);

      //this.messagesMap[this.currentExpertId].push(msg);
      this.input = '';
      this.$nextTick(this.scrollToBottom);
    },
    scrollToBottom() {
      const box = this.$refs.msgBox;
      if (box) box.scrollTop = box.scrollHeight;
    },
    getImageUrl(url) {
      if (!url) return '';
      return url.startsWith('/api') ? url : `/api${url}`;
    },
    formatTime(time) {
      if (!time) return '';
      if (typeof time === 'string') {
        // 兼容 ISO 字符串和 yyyy-MM-dd HH:mm:ss
        if (time.includes('T')) {
          return time.replace('T', ' ').substring(0, 19);
        }
        return time.substring(0, 19);
      }
      if (typeof time === 'number') {
        // 毫秒时间戳
        const date = new Date(time);
        const pad = n => n < 10 ? '0' + n : n;
        return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
      }
      if (time instanceof Date) {
        const pad = n => n < 10 ? '0' + n : n;
        return `${time.getFullYear()}-${pad(time.getMonth() + 1)}-${pad(time.getDate())} ${pad(time.getHours())}:${pad(time.getMinutes())}:${pad(time.getSeconds())}`;
      }
      return String(time);
    },
  },
  mounted() {
    this.loadSessions();
    connectChatSocket({
      userId: this.userInfo.id,
      role: 'user',
      onMessage: this.handleSocketMessage
    });
  },
  beforeDestroy() {
    closeChatSocket();
  },
  computed: {
    messages() {
      return this.messagesMap[this.currentExpertId] || [];
    }
  }
};
</script>
<style scoped>
.im-container {
  display: flex;
  width: 100%;
  max-width: 1100px;
  min-height: 600px;
  margin: 40px auto;
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 4px 24px #e6e8f0;
  overflow: hidden;
}
.session-list {
  width: 240px;
  background: #f7f8fa;
  border-right: 1px solid #e6e8f0;
  display: flex;
  flex-direction: column;
}
.session-title {
  font-size: 18px;
  font-weight: bold;
  padding: 18px 20px 10px 20px;
  border-bottom: 1px solid #e6e8f0;
}
.session-scroll {
  flex: 1;
  padding: 10px 0;
}
.session-item {
  display: flex;
  align-items: center;
  padding: 12px 18px;
  cursor: pointer;
  border-radius: 8px;
  margin: 4px 8px;
  transition: background 0.2s;
}
.session-item.active, .session-item:hover {
  background: #e6f7ff;
}
.session-info {
  margin-left: 12px;
}
.session-info .name {
  font-weight: bold;
  font-size: 15px;
}
.session-info .desc {
  color: #888;
  font-size: 13px;
}
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  max-height: 800px;
  overflow: auto;
}
.chat-header {
  font-size: 17px;
  font-weight: bold;
  padding: 18px 24px;
  border-bottom: 1px solid #e6e8f0;
  display: flex;
  align-items: center;
  gap: 16px;
}
.chat-title-desc {
  color: #409EFF;
  font-size: 14px;
  font-weight: normal;
}
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 18px 24px;
  background: #f7f8fa;
}
.chat-msg {
  display: flex;
  margin-bottom: 14px;
  align-items: flex-end;
}
.chat-msg.left {
  flex-direction: row;
}
.chat-msg.right {
  flex-direction: row-reverse;
}
.bubble {
  max-width: 60%;
  background: #fff;
  border-radius: 16px;
  padding: 10px 16px;
  font-size: 15px;
  margin: 0 10px;
  box-shadow: 0 2px 8px #e6e8f0;
  word-break: break-all;
}
.chat-msg.right .bubble {
  background: #cce6ff;
}
.role {
  font-weight: bold;
  margin-right: 6px;
  color: #409EFF;
}
.time {
  font-size: 12px;
  color: #888;
  margin-left: 8px;
}
.chat-input-row {
  display: flex;
  gap: 10px;
  align-items: center;
  padding: 18px 24px;
  border-top: 1px solid #e6e8f0;
  background: #fff;
}
.chat-input {
  flex: 1;
}
</style>
